package com.ygsoft.nio.server.filemanager;

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.Logger;

public class ReadWorker implements Runnable {
	
	private LinkedBlockingQueue<ServerDataEvent> lbQueue = null;
	private Logger log = Logger.getLogger(ReadWorker.class);
	private byte[] readBuf = new byte[4096];
	
	
	public ReadWorker(){
		this.lbQueue = new LinkedBlockingQueue<ServerDataEvent>();
	}
	
	@Override
	public void run() {
		log.debug("Start Read Worker..");
		while(true){
			try {
				log.debug("Wait EV in Read Worker");
				ServerDataEvent ev = this.lbQueue.take();
				this.procData(ev);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void procData(ServerDataEvent ev){
		log.debug("Process data from server..");
		byte[] dt = ev.data;
		InputStream is = new ByteArrayInputStream(dt);
		DataInputStream dis = new DataInputStream(is);
		
		try {
			int readLength = dis.readInt();
			log.debug("Read Length : " + readLength);
			int read = dis.read(this.readBuf, 0, readLength);
			log.debug("read : readBuffer = " + read + " : " + readLength);
			
			String filePath = new String(this.readBuf, 0, readLength);
			log.debug("File Path : " + filePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void addNewEvent(ServerDataEvent event){
		log.debug("Data Evnet added..");
		synchronized(this.lbQueue){
			this.lbQueue.add(event);
		}
	}
}
